import React, {Component} from 'react';
import {dark, light, baseURL} from '../../config';
import {
  Appearance,
  StyleSheet,
  StatusBar,
  ScrollView,
  Text,
  View,
  Image,
  TouchableOpacity,
  Modal,
  TextInput,
} from 'react-native';
import {connect} from 'react-redux';
import {NavigationContext} from '@react-navigation/native';
import {Icon, Toast} from '@ant-design/react-native';
import {pxToDp} from '../../utils/stylesKits';
import storage from '../../utils/storage';
import {setUserInfo} from '../../store/actions';
import Cell from '../../components/Cell';
import {updateJfUser} from '../../api/user';
import {uploadPic} from '../../api/upload';
import ImagePicker from 'react-native-image-crop-picker';

/**
 * APP EditUser 页面
 * @colorScheme 用户手机主题模式 是否开启了黑夜模式
 * */
const colorScheme = Appearance.getColorScheme() === 'dark' ? dark : light;

class EditUser extends Component {
  static contextType = NavigationContext;

  constructor(props) {
    super(props);
    this.state = {
      userInfo: props.userInfo,
      modalVisible: false,
      inputValue: '的的大啊啊啊',
      field: '',
    };
  }

  hideModal = () => this.setState(() => ({modalVisible: false}));

  showModal = async (inputValue, field) => {
    await this.setState(() => ({inputValue, field}));
    this.setState(() => ({modalVisible: true}));
  };

  onChangeText = text => this.setState(() => ({inputValue: text}));

  // 点击了 设置头像按钮
  onChangeAvatar = async () => {
    let image = null;
    try {
      image = await ImagePicker.openPicker({
        width: 300,
        height: 400,
        cropping: true,
      });
    } catch (error) {
      Toast.fail('文件格式不支持', 2, null, false);
    }
    let logining = null;
    try {
      let formData = new FormData();
      formData.append('pic', {
        // 本地图片的地址
        uri: image.path,
        // 图片的类型
        type: image.mime,
        // 图片的名称 file:///......../d343.jpg
        name: image.path.split('/').pop(),
      });
      logining = Toast.loading('请稍等...', 8);
      // 开始上传
      const res = await uploadPic(formData);
      Toast.remove(logining);
      if (res.status !== 200) {
        Toast.fail(res.msg, 2, null, false);
        return;
      }
      Toast.success('已经上传，点击保存生效', 2, null, false);
      const {userInfo} = this.state;
      userInfo.avatar = res.data;
      this.setState(() => ({userInfo}));
    } catch (error) {
      Toast.fail(String(error), 2, null, false);
      Toast.remove(logining);
    }
  };

  saveInputValue = () => {
    const {userInfo, inputValue, field} = this.state;
    userInfo[field] = inputValue;
    if (field) {
      this.setState(() => ({userInfo}));
    }
    this.setState(() => ({modalVisible: false}));
  };

  saveUserInfo = async () => {
    const {userInfo} = this.state;
    if (!userInfo.nickname) {
      Toast.fail('用户名还是要有的', 2, null, false);
      return;
    }
    const data = {
      id: userInfo.id,
      nickname: userInfo.nickname,
      job_title: userInfo.job_title,
      avatar: userInfo.avatar,
      introduction: userInfo.introduction,
    };
    let logining = Toast.loading('请稍等...', 8);
    const res = await updateJfUser(data);
    Toast.remove(logining);
    if (res.status !== 200) {
      Toast.fail(res.msg, 2, null, false);
      return;
    }
    Toast.success('修改成功', 2, null, false);
    storage.save({
      key: 'userInfo',
      data: userInfo,
    });
    this.props.setUserInfo({userInfo});
  };

  componentDidMount() {}

  componentDidUpdate(prevProps, prevState) {}

  componentWillUnmount() {}

  render() {
    const {userInfo, modalVisible, inputValue} = this.state;
    return (
      <View style={styles.container}>
        <StatusBar
          backgroundColor="transparent"
          barStyle={colorScheme.barStyle}
          translucent={true}
        />
        <Cell
          style={{...styles.cell, ...styles.avatarCell}}
          label="头像"
          onClick={() => this.onChangeAvatar()}>
          <Image
            style={styles.avatar}
            source={{
              uri: `${baseURL}${userInfo.avatar}`,
            }}
          />
        </Cell>
        <Cell
          style={styles.cell}
          label="用户名"
          onClick={() => this.showModal(userInfo.nickname, 'nickname')}>
          <Text>{userInfo.nickname}</Text>
        </Cell>
        <Cell
          style={styles.cell}
          label="职位"
          onClick={() => this.showModal(userInfo.job_title, 'job_title')}>
          <Text>{userInfo.job_title}</Text>
        </Cell>
        <Cell
          style={styles.cell}
          label="简介"
          onClick={() => this.showModal(userInfo.introduction, 'introduction')}>
          <Text>{userInfo.introduction}</Text>
        </Cell>
        <TouchableOpacity onPress={() => this.saveUserInfo()}>
          <Text style={styles.saveBtn}>保 存</Text>
        </TouchableOpacity>
        <Modal
          animationType="fade"
          transparent={true}
          visible={modalVisible}
          onRequestClose={this.hideModal}>
          <TouchableOpacity style={styles.Modal} onPress={this.hideModal}>
            <View style={styles.inputView}>
              <TextInput
                autoFocus={true}
                style={styles.textInput}
                onChangeText={text => this.onChangeText(text)}
                value={inputValue}
                placeholderTextColor={colorScheme.color}
                placeholder="请输入..."
                multiline={true}
                textAlignVertical="top"
              />
              <TouchableOpacity onPress={() => this.saveInputValue()}>
                <Text style={styles.inputBtn}>确定</Text>
              </TouchableOpacity>
            </View>
          </TouchableOpacity>
        </Modal>
      </View>
    );
  }
}

const mapStateToProps = state => ({userInfo: state.$userInfo.userInfo});
const mapDispatchToProps = dispatch => {
  return {
    setUserInfo: userInfo => {
      dispatch(setUserInfo(userInfo));
    },
  };
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    paddingTop: pxToDp(45),
    backgroundColor: colorScheme.backgroundColor,
  },
  cell: {
    backgroundColor: colorScheme.backgroundColorB,
    marginTop: pxToDp(1),
  },
  avatarCell: {
    marginTop: pxToDp(10),
    marginBottom: pxToDp(10),
  },
  avatar: {
    width: pxToDp(56),
    height: pxToDp(56),
    borderRadius: pxToDp(28),
  },
  saveBtn: {
    marginTop: pxToDp(28),
    padding: pxToDp(8),
    marginLeft: pxToDp(20),
    marginRight: pxToDp(20),
    color: '#38badc',
    borderWidth: pxToDp(1),
    borderColor: '#38badc',
    borderRadius: pxToDp(5),
    textAlign: 'center',
  },
  Modal: {
    width: '100%',
    height: '100%',
    backgroundColor: colorScheme.backgroundColor,
    opacity: 0.6,
  },
  inputView: {
    position: 'absolute',
    bottom: 0,
    alignItems: 'flex-end',
    width: '100%',
    padding: pxToDp(20),
    backgroundColor: colorScheme.backgroundColorB,
  },
  textInput: {
    alignItems: 'flex-start',
    width: '100%',
    minHeight: pxToDp(120),
    padding: pxToDp(8),
    borderRadius: pxToDp(5),
    backgroundColor: colorScheme.backgroundColorC,
    fontSize: pxToDp(14),
    lineHeight: pxToDp(14),
  },
  inputBtn: {
    width: pxToDp(56),
    marginTop: pxToDp(15),
    padding: pxToDp(3),
    color: colorScheme.color,
    fontSize: pxToDp(16),
    textAlign: 'center',
    backgroundColor: '#2388d8',
    borderRadius: pxToDp(15),
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(EditUser);
